package com.uranus.auth.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.EncryptUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uranus.auth.auth.beans.JwtToken;
import com.uranus.auth.auth.beans.User;
import com.uranus.auth.auth.mapper.UserMapper;
import com.uranus.auth.auth.request.captcha.SendCaptchaRequest;
import com.uranus.auth.auth.request.user.*;
import com.uranus.auth.auth.response.user.UserResponse;
import com.uranus.auth.auth.service.CaptchaService;
import com.uranus.auth.auth.service.JwtService;
import com.uranus.auth.auth.service.UserService;
import com.uranus.common.VO.ServiceContext;
import com.uranus.common.VO.paging.Paginator;
import com.uranus.common.VO.paging.PagingRequest;
import com.uranus.common.bean.expection.BusinessException;
import com.uranus.common.bean.expection.ParamsException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uranus.common.VO.Result;
import com.uranus.common.common.beans.Dict;
import com.uranus.common.common.service.CodeMessageService;
import com.uranus.common.common.service.DictService;
import com.uranus.common.common.service.IdPoolService;
import com.uranus.common.constant.ServicesConstant;
import com.uranus.common.constant.enums.LoginTypeEnum;
import com.uranus.common.util.Encrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ybx
 * @since 2018-12-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private CodeMessageService codeMsgService;
    @Autowired
    private JwtService jwtService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result login(LoginRequest req) {
        if(!StringUtils.hasLength(req.getLoginName())){
            throw new ParamsException("请输入手机号/用户名登录");
        }
        if(!StringUtils.hasLength(req.getPassword())){
            throw new ParamsException("请输入密码");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(req.getLoginType()== LoginTypeEnum.mobile){
            queryWrapper.eq("mobile",req.getLoginName());
        }else {
            queryWrapper.eq("email",req.getLoginName());
        }
        User user=this.baseMapper.selectOne(queryWrapper);
        if(user==null){
            throw new BusinessException(codeMsgService.queryCodeMessage(10400002));//10400002:用户不存在
        }
        return Result.buildSuccess(jwtService.buildJwtUser(user));
    }

    @Override
    public Result register(RegisterRequest request) {
        Result result= checkByLoginType(request.getLoginType(),request.getLoginName());
        if(result.isSuccess()){
            throw new BusinessException(String.format("%s 已注册,请直接登录!"));
        }
        // check checkCaptcha
        SendCaptchaRequest sendCaptchaReq=new SendCaptchaRequest(){};
        sendCaptchaReq.setCaptchaType(1);
        sendCaptchaReq.setReceiver(request.getLoginName());
        captchaService.checkCaptcha(sendCaptchaReq,request.getCaptcha());
        User user=new User();
        if(request.getLoginType()==LoginTypeEnum.mobile){
            user.setMobile(request.getLoginName());
        }
        if(request.getLoginType()==LoginTypeEnum.email){
            user.setEmail(request.getLoginName());
        }
        user.setSalt(Encrypt.getRandomString(6));
        user.setPassword(Encrypt.ToMd5Encrypt(request.getPassword() + user.getSalt()));
        user.setRoleId(1);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        this.save(user);

        //TODO Call trade service return account_address
        return Result.buildSuccess(jwtService.buildJwtUser(user));
    }

    @Override
    public Result update(UpdateUserRequest req) {
        if(ServiceContext.getInstance().getUserId()!=req.getId() && ServiceContext.getInstance().getRoleId()==1 ){
            throw new ParamsException("当前登录用户无法修改其他用户信息");
        }
        User user= baseMapper.selectById(req.getId());
        if(user==null){
            throw new ParamsException("用户不存在");
        }
        user.setNickName(req.getNickName());
        user.setUpdateTime(new Date());
        if(req.getRoleId()!=null){
            user.setRoleId(req.getRoleId());
        }
        this.baseMapper.updateById(user);
        return Result.buildSuccess();
    }

    @Override
    public Result updatePassword(UpdatePasswordRequest req) {
        if(ServiceContext.getInstance().getUserId()!=req.getId() && ServiceContext.getInstance().getRoleId()==1 ){
            throw new ParamsException("当前登录用户无法修改其他用户信息");
        }
        User user= baseMapper.selectById(req.getId());
        if(user==null){
            throw new ParamsException("用户不存在");
        }
        String encryptPwd = Encrypt.ToMd5Encrypt(req.getOldPassword() + user.getSalt());
        String newencryptPwd =Encrypt.ToMd5Encrypt(req.getNewPassword() + user.getSalt());
        if (!encryptPwd.equals(user.getPassword())) {
            throw new ParamsException("原密码错误");
        }
        if(encryptPwd.equals(newencryptPwd)){
            throw new ParamsException("新密码和原密码相同");
        }
        user.setPassword(newencryptPwd);
        user.setUpdateTime(new Date());
        this.baseMapper.updateById(user);
        return Result.buildSuccess();
    }

    @Override
    public Result forgetPassword(ForgetPasswordRequest request) {
        return null;
    }

    @Override
    public Result bindMobile(BindMobileRequest request) {
        return null;
    }

    @Override
    public Result bindEmail(BindMobileRequest request) {
        return null;
    }

    @Override
    public Result queryById(Integer id) {
        if(ServiceContext.getInstance().getUserId()!=id && ServiceContext.getInstance().getRoleId()==1){
            throw new ParamsException("当前登录用户无法获取其他用户详情");
        }
        User user= baseMapper.selectById(id);
        if(user==null){
            throw new ParamsException("用户不存在");
        }
        UserResponse userResponse=new UserResponse();
        BeanUtils.copyProperties(user, userResponse);
        return Result.buildSuccess(userResponse);
    }

    @Override
    public Result checkByLoginType(LoginTypeEnum loginType,String checkValue) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(loginType==LoginTypeEnum.mobile){
            queryWrapper .eq("mobile",checkValue);
        }else{
            if(!Pattern.matches(ServicesConstant.RegexEmail, checkValue.trim())){
                throw new ParamsException("请输入正确的邮箱");
            }
            queryWrapper .eq("email",checkValue);
        }
        User user= baseMapper.selectOne(queryWrapper);
        if(user==null || user.getId()==null){
            return Result.buildError();
        }
        return Result.buildSuccess();
    }

    @Override
    public Result search(QueryUserRequest request) {
        Page<UserResponse> page =new Page<>(request.getPage(), request.getPageSize());
        page.setDesc(request.getSort());
        IPage<UserResponse> list=userMapper.searchPagerUser(page,request);
        return Result.buildSuccess(list);
    }
}
